package com.qdxwx.web.controller.user;

import com.qdxwx.common.exception.AccountException;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.account.UserAccountDetailService;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.bank.BankCardService;
import com.qdxwx.data.service.card.CardCodeService;
import com.qdxwx.data.service.card.CardService;
import com.qdxwx.data.service.cash.CashApplyService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.bank.BankCard;
import com.qdxwx.models.card.Card;
import com.qdxwx.models.card.CardCode;
import com.qdxwx.models.cash.CashApply;
import com.qdxwx.models.enums.*;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserAccountController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserAccountController.class);

    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserAccountDetailService userAccountDetailService;
    @Autowired
    private CardCodeService cardCodeService;
    @Autowired
    private WebsiteProfileService websiteProfileService;
    @Autowired
    private CashApplyService cashApplyService;
    @Autowired
    private BankCardService bankCardService;
    @Autowired
    private CardService cardService;

    /**
     * 我的账户
     */
    @RequestMapping("/account.html")
    public String myAccount(HttpServletRequest request, ModelMap mmap) throws AccountException {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return "redirect:/auth/login.html";
        }
        String type = request.getParameter("actHistoryType");
        if (type == null) {
            type = "";
        }
        String accountTypeName = "";
        switch (type) {
            case "":
                accountTypeName = "全部";
                break;
            case "SALES":
                accountTypeName = "站内消费";
                break;
            case "CASHLOAD":
                accountTypeName = "账户充值";
                break;
            case "VMLOAD":
                accountTypeName = "充值卡充值";
                break;
            case "DRAWMONEY":
                accountTypeName = "余额提现";
                break;
            case "BACKMONEY":
                accountTypeName = "返现";
                break;
            case "ADMINLOAD":
                accountTypeName = "后台充值";
                break;
            default:
        }
        mmap.put("accountTypeName", accountTypeName);
        long userId = user.getUserId();
        UserAccount userAccount = userAccountService.getByUserId(userId);
        mmap.put("userAccount", userAccount);

        UserAccountDetail query = new UserAccountDetail();
        query.setActHistoryType(type);
        query.setUserId(userId);
        long rows = userAccountDetailService.count(query);
        PageRequest page = new PageRequest();
        int currentPage = TKConvert.toInteger(request.getParameter("page"));
        page.setCurrentPage(currentPage);
        page.setPageSize(6);
        mmap.put("totalPages", page.getTotalPages(rows));
        List<UserAccountDetail> accList = userAccountDetailService.getList(query, page);
        mmap.put("accList", accList);
        mmap.put("page", page);
        mmap.put("queryUserAccountDetail", query);
        mmap.put("actHistoryType", type);
        mmap.put("user", user);
        if (TKRequest.isMobileBrowse(request)) {
            return getViewPathH5("user/uc-account");
        }
        return getViewPath("ucenter/uc-account");
    }

    @RequestMapping("/account/recharge.html")
    public String showRecharge(HttpServletRequest request, ModelMap mmap) {

        return getViewPath("ucenter/uc-account-recharge");
    }

    /**
     * 充值卡激活
     */
    @RequestMapping("/account/recharge.json")
    @ResponseBody
    public AjaxResult recharge(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.auth("登录超时");
        }
        /*充值卡卡号*/
        String code = TKString.trim(request.getParameter("cardCode"));
        /*充值卡密码*/
        String pwd = TKString.trim(request.getParameter("cardPwd"));
        CardCode cardCode = cardCodeService.getByCode(code, pwd);
        if (cardCode == null) {
            return AjaxResult.error("卡号或密码错误，请确认，谢谢！");
        }
        if (cardCode.getStatus().equals(CardStatus.USED.toString())) {
            return AjaxResult.error("该卡已被使用，不能再次使用！");//已经使用
        } else if (cardCode.getStatus().equals(CardStatus.CLOSE.toString())) {
            return AjaxResult.error("该卡已作废，不能再次使用！");//已关闭
        } else if (cardCode.getStatus().equals(CardStatus.OVERDUE.toString())) {
            return AjaxResult.error("该卡已过期，不能再次使用！");//已过期
        }
        Card card = cardService.get(cardCode.getCardId());
        if (card.getTypeId() != 2) {
            return AjaxResult.error("卡号或密码错误，请确认输入是否正确！");//类型不匹配
        }
        //不在有效期内
        LocalDate nowDate = LocalDate.now();
        if (nowDate.isBefore(card.getBeginDate()) || nowDate.isAfter(card.getEndDate())) {
            return AjaxResult.error("该卡不在有效期内，请确认！");
        }
        // 充值卡信息改变
        cardCode.setUserId(user.getUserId());
        cardCode.setUserName(user.getDisplayName());
        cardCode.setOrderId(0);
        int count = cardCodeService.updateUsed(cardCode);
        if (count > 0) {
            /*更新账户信息*/
            UserAccount userAccount = userAccountService.getByUserId(user.getUserId());
            /*账户余额加上充值卡金额*/
            userAccount.setBalance(userAccount.getBalance() + card.getMoney());
            /*充值余额加上充值卡金额*/
            userAccount.setVmAmount(userAccount.getVmAmount() + card.getMoney());
            /*最后操作时间*/
            userAccountService.update(userAccount);
            /*充值记录*/
            UserAccountDetail detail = new UserAccountDetail();
            detail.setUserId(user.getUserId());
            detail.setOrderId(0);// 订单id
            /*充值卡code id*/
            detail.setOtherId(cardCode.getId());
            detail.setBalance(userAccount.getBalance());// 当前余额
            detail.setVmAmount(userAccount.getVmAmount());// vm余额
            detail.setBackAmount(userAccount.getBackAmount());// 提现余额
            detail.setOrderAmount(card.getMoney());// 交易金额
            detail.setDescription("充值卡充值(" + cardCode.getCardCode() + ")");// 账户历史内容描述
            detail.setActHistoryType(AccountHistoryType.VMLOAD.toString());// 帐务类型.充值
            detail.setBizType(AccountBizType.CARDLOAD.toString());// 业务类型充值卡
            detail.setVersion(userAccount.getVersion());// 乐观锁版本号
            userAccountDetailService.insert(detail);
            return AjaxResult.success();
        } else {
            logger.error("使用充值卡失败：" + cardCode);
            return AjaxResult.error("充值卡可能已被使用，如有疑问，请与本网客服联系！");
        }
    }

    @RequestMapping("/account/draw.html")
    public String showDraw(HttpServletRequest request, ModelMap mmap) {
        long userId = LoginUser.getUserId(request);
        UserAccount userAccount = userAccountService.getByUserId(userId);
        BankCard bankCard = new BankCard();
        bankCard.setInfoId(userId);
        bankCard.setType(BankCardType.TEACHER.toString());
        List<BankCard> bankCardList = bankCardService.getList(bankCard, new PageRequest(1, 3));
        Map<String, Object> serviceSwitch = websiteProfileService.getMap(WebsiteProfileType.serviceSwitch.toString());
        mmap.put("allowDraw", serviceSwitch.get("allowDraw"));
        mmap.put("userAccount", userAccount);
        mmap.put("bankCardList", bankCardList);
        return getViewPath("ucenter/uc-account-draw");
    }

    /**
     * 提现
     */
    @RequestMapping("/account/draw.json")
    @ResponseBody
    public AjaxResult saveDraw(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) return AjaxResult.error("登录超时");
        //提现开关
        Map<String, Object> serviceSwitch = websiteProfileService.getMap(WebsiteProfileType.serviceSwitch.toString());
        if (!(serviceSwitch.get("allowDraw") + "").equals("ON")) {
            return AjaxResult.error("暂不支持提现");
        }
        /*提取金额*/
        int drawMoney = Double.valueOf(TKConvert.toDouble(request.getParameter("drawMoney")) * 100).intValue();
        if (drawMoney < 10000 || (drawMoney % 10000 > 0)) return AjaxResult.error("提现金额必须是100的倍数，最低提现100元");
        /*收款人*/
        String bankCardName = request.getParameter("bankCardName");
        if (TKString.isEmpty(bankCardName)) return AjaxResult.error("请输入银行卡开户人");
        /*银行卡号*/
        String bankCardNumber = request.getParameter("bankCardNumber");
        if (TKString.isEmpty(bankCardNumber)) return AjaxResult.error("请输入银行卡号");
        /*转账银行*/
        String bankName = request.getParameter("bankName");
        if (TKString.isEmpty(bankName)) return AjaxResult.error("请输入开户银行");
        UserAccount userAccount = userAccountService.getByUserId(user.getUserId());
        if (userAccount == null) return AjaxResult.error("账户异常，找不到指定账户");
        if (userAccount.getAccountStatus().equals(AccountStatus.FROZEN.toString()))
            return AjaxResult.error("账户被冻结，请联系管理员");
        if (userAccount.getBackAmount() < drawMoney) {
            return AjaxResult.error("可提现金额不足");
        }

        /*冻结提现金额*/
        userAccount.setFrozenAmount(userAccount.getFrozenAmount() + drawMoney);
        /*余额减掉要提取的金额*/
        userAccount.setBalance(userAccount.getBalance() - drawMoney);
        /*返现余额减掉要提取的金额*/
        userAccount.setBackAmount(userAccount.getBackAmount() - drawMoney);
        userAccount.setVersion(userAccount.getVersion() + 1);
        /*更新账户信息*/
        int row = userAccountService.update(userAccount);
        if (row > 0) {
            /*创建提现交易记录*/
            UserAccountDetail userAccountDetail = new UserAccountDetail();
            userAccountDetail.setUserId(user.getUserId());
            userAccountDetail.setActHistoryType(AccountHistoryType.DRAWMONEY.toString());
            userAccountDetail.setBalance(userAccount.getBalance());
            userAccountDetail.setBackAmount(userAccount.getBackAmount());
            userAccountDetail.setOrderAmount(drawMoney);
            userAccountDetail.setDescription("提现金额" + (drawMoney / 100) + "元");
            userAccountDetail.setBizType(AccountBizType.DRAWMONEY.toString());
            userAccountDetail.setVmAmount(userAccount.getVmAmount());
            userAccountDetail.setVersion(userAccount.getVersion());
            userAccountDetailService.insert(userAccountDetail);
            /*创建申请提现记录*/
            CashApply cashApply = new CashApply();
            cashApply.setInfoId((int) user.getUserId());
            cashApply.setInfoName(user.getUserName());
            cashApply.setType(BankCardType.TEACHER.toString());
            cashApply.setAmount(drawMoney);
            cashApply.setBankCardNumber(bankCardNumber);
            cashApply.setBankName(bankName);
            cashApply.setBankCardName(bankCardName);
            cashApply.setStatus(CashApplyStatus.NOTAPPROVED.getValue());
            cashApply.setDescription("提现金额" + (drawMoney / 100) + "元");
            cashApplyService.insert(cashApply);
            /*创建历史提现卡号*/
            BankCard bankCard = new BankCard();
            bankCard.setInfoId(user.getUserId());
            bankCard.setType(BankCardType.TEACHER.toString());
            bankCard.setBankCardNumber(bankCardNumber);
            int count = bankCardService.count(bankCard);
            if (count < 1) {
                bankCard.setBankName(bankName);
                bankCard.setBankCardName(bankCardName);
                bankCardService.insert(bankCard);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("提成操作失败，请稍后再试");
        }

    }

    /**
     * 选择银行卡号
     */
    @RequestMapping("/account/bank/select.json")
    @ResponseBody
    public AjaxResult getBank(HttpServletRequest request) {
        long id = TKConvert.toLong(request.getParameter("id"));
        if(id < 1) return AjaxResult.error("选择错误");
        BankCard bankCard = bankCardService.get(id);
        if(bankCard == null) return AjaxResult.error("选择错误");
        return AjaxResult.success(bankCard);
    }
}
